using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Configuration;
using System.Runtime.Serialization;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using T.FAS.Runtime.DataAccess.SPI;
using T.FAS.Runtime.DataAccess.Service;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.DataModel.Dao;
using T.FAS.Runtime.DataAccess.ShardingRule;
using T.FAS.Runtime.DataAccess.SQLDom;
using T.FAS.Runtime.DataAccess.Common;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.DataModel.Plugin;
using T.FAS.Runtime.DataAccess.Engine;
using System.Threading;
using AppContext = T.ServiceComponent.Session.Service.AppContext;
using Newtonsoft.Json.Linq;

namespace T.FAS.Runtime.DataAccess.UnitTest
{
    [TestClass]
    public class CDOEngineTest_PostgreSQL
    {
        //public const string cdoID = "1c310fa6-2b13-4f92-8259-a7868171821e";//xer
        public const string cdoID = "7246879b-d0be-4c4d-886a-09eb8cb0507e";//liufei
        //public const string dqID = "15c1f358-4f49-4f98-8675-ab2feb869b1a";  //xer
        public const string dqID = "531885ab-96aa-4a62-bdaa-1cf127fd45a6";  //liufei
        CompositeDataObjectRTPManager _cdoManager = new CompositeDataObjectRTPManager();
        DataQueryRTPManager _dqManager = new DataQueryRTPManager();
        private readonly ChangeSetService _changeService = new ChangeSetService();
        static CompositeDataObject cdo;
        DataQuery dq;
        TRecord templateTRecord;
        

        [TestInitialize]
        public void Init()
        {
            LiveDebug.IsDebug = true;
            LiveDebug.IsAllAuth = true;
            //初始化cdo
            GetCDOMeta(cdoID);

            dq = _dqManager.GetMetaDataContent(dqID) as DataQuery;
            PackageDQMetaData(dq);

            JObject obj = JObject.Parse(json);
            templateTRecord = TRecord.BuildRecord(obj);
        }

        private CompositeDataObject GetCDOMeta(string cdoID)
        {
            cdo = _cdoManager.GetMetaDataContent(cdoID) as CompositeDataObject;
            PackageCDOMetaData(cdo);
            cdo.BuildModelObjectRelation();
            cdo.RootCompositeNodeObject.Associations.ForEach(asso =>
            {
                if (asso.AssociateType == AssociateType.OuterLeftJoin)
                {
                    asso.AssoDataObject = new DataObject();
                }
            });
            return cdo;
        }

        string json3 = @"{
    ""ID"": ""f48e2205-444d-6431-8aee-a170dae8c14d"",
    ""Code"": ""001"",
    ""Name"": ""掩码测试"",
    ""Mobile"": ""12345678901"",
    ""Mobile_mask"": """",
    ""Email"": ""12345678901@qq.com"",
    ""IDCardNo"": ""370123456789098765"",
    ""IDCardNo_mask"": """",
}";

        string json = $@"{{
			'ID': '{pk}',
			'Code': '44',
			'Name': '44',
			't_datetime': '2024-12-09 14:49',
			'Creator': '',
			'CreatorName': '',
			'CreateTime': '',
			'LastModifier': '',
			'LastModifierName': '',
			'LastModifyTime': ''
		}}";


        static string pk = "f762614b-04c0-4c0f-cb2e-699a5ca3cd15";

        [TestMethod]
        public void TestGetMask()
        {
            var context = new Dictionary<string, object>
            {
                {DACConst.ExtSetting,  "{\"isAll\":false,\"columns\":[\"Mobile\", \"IDCardNo\"]}"},
            };
            TRecord tRecord = QueryRecord(context);
            Console.WriteLine(TRecord.ToJson(tRecord));
        }

        public static TRecord QueryRecord(Dictionary<string, object> context)
        {
            TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().QueryDataForCDO(cdo, pk, context);
            TRecord tRecord = ((TCommonResult<TRecord>)tResult).Record;
            return tRecord;
        }

        [TestMethod]
        public void TestSaveMask()
        {
            try
            {
                try
                {
                    UnifiedDataAccessServiceFactory.GetInstance().DeleteDataSetForCDO(cdo, new List<string> { pk });
                } 
                catch
                {
                }

                TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().SaveDataForCDO(cdo, templateTRecord);
                var tRecord = ((TCommonResult<TRecord>)tResult).Record;
            }
            catch (Exception e)
            {

                throw;
            }
        }

        [TestMethod]
        public void TestUpdateMask()
        {
            try
            {
                //TestSaveMask();
                var context = new Dictionary<string, object>
                {
                    {DACConst.ExtSetting,  "{\"isAll\":true,\"columns\":[\"Mobile\", \"IDCardNo\"]}"},
                };
                TRecord updateTRecord = QueryRecord(context);
                updateTRecord = TRecord.BuildRecord(JObject.Parse(json));

                //第一次更新，获取变更日志
                var change1 = _changeService.GetChangeSet(cdo, ChangeSetType.Update, updateTRecord);
                TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().UpdateDataForCDO(cdo, updateTRecord);
                var tRecord = ((TCommonResult<TRecord>)tResult).Record;
            }
            catch (Exception e)
            {

                throw;
            }
        }

        [TestMethod]
        public void TestDQQuery()
        {
            Dictionary<string, object> parameters = new Dictionary<string, object> {
                //{DACConst.ExtSetting,"{\"isAll\":false,\"columns\":[\"Mobile\", \"IDCardNo\"]}" }
            };
            var result = UnifiedDataAccessServiceFactory.GetInstance().QueryDataForDataQuery(dq, parameters);
            Console.WriteLine(JsonConvert.SerializeObject(result));
        }


        private void PackageCDOMetaData(CompositeDataObject cdo)
        {
            DACLocalTestTool.PackagingDependencyMetaData(cdo, true);
        }

        private void PackageDQMetaData(DataQuery dq)
        {
            DACLocalTestTool.InitializeDQ(dq, isGetFromDB: true);
        }


        [TestMethod]
        public void Test商机六位小数精度更新问题()
        {
            try
            {
                var cdo = _cdoManager.GetMetaDataContent("18d15a52-4ca9-41d9-ae04-a9b3512b0774") as CompositeDataObject;
                PackageCDOMetaData(cdo);

                var json = @"{
			        ""ID"": ""e5e20fbf-5bd4-1f5b-e72c-343a0f44a67a"",
			        ""ClassificationType"": """",
			        ""PricingCoefficient"": 0.000001,
			        ""Creator"": """",
			        ""CreatorName"": ""user2"",
			        ""CreateTime"": ""2024-04-19+11:04:14"",
			        ""LastModifier"": """",
			        ""LastModifierName"": """",
			        ""LastModifyTime"": """",
			        ""IsDel"": 0,
			        ""ClassificationCode"": ""GSFL00032"",
			        ""ClassificationName"": ""3333"",
			        ""Note"": """"
		        }";
                var context = new Dictionary<string, object>
                {

                };
                var record = TRecord.BuildRecord(JObject.Parse(json));
                TResult tResult = UnifiedDataAccessServiceFactory.GetInstance().SaveDataForCDO(cdo, record);
                var tRecord = ((TCommonResult<TRecord>)tResult).Record;
            }
            catch (Exception e)
            {
                throw;
            }
        }
    }
}
